<?php

declare (strict_types=1);
/**
 * @copyright 深圳市易果网络科技有限公司
 * @version 1.0.0
 * @link https://dayiguo.com
 */

namespace App\Kernel\Traits;
use Hyperf\Database\Model\Builder;

/**
 * Class
 *
 * @author 刘兴永(aile8880@qq.com)
 * @package App\Kernel\Traits
 */
trait QueryTrait
{
    /**
     * 生成查询条件
     *
     * @param Builder $query
     * @param array $maps
     * @return Builder
     */
    public function genQuery(Builder $query, array $maps)
    {
        foreach ($maps as $map) {
            $keys = array_keys($map);
            if (!isset($keys[0])) continue;

            $field = $keys[0];
            $condition = $map[$keys[0]];

            if (!is_array($condition)) {
                // 原始查询
                if ($field === '__RAW__') {
                    $query->whereRaw($condition);
                    continue;
                }
                // 普通查询
                else {
                    $query->where($field, $condition);
                    continue;
                }
            }

            if (is_array($condition)) {
                switch (strtolower($condition[0])) {
                    case 'in':
                        $query->whereIn($field, $condition[1]);
                        break;

                    case 'not in':
                        $query->whereNotIn($field, $condition[1]);
                        break;

                    case 'between':
                        $query->whereBetween($field, $condition[1]);
                        break;

                    default:
                        $query->where($field, $condition[0], $condition[1]);
                }
            }
        }

        return $query;
    }
}